<?php

namespace App\Http\Middleware;

use App\Http\Dao\WechatUserDao;
use App\Http\Services\common\JwtService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;

class CheckToken
{
    public $errorMsg = [
        'code' => 1,
        'msg' => 'success'
    ];

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     * @return Response|RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 验证token
        $token = $request->header('authorization');
        $token = str_replace('Bearer ', '', $token);
        if (empty($token) || $token == 'null') {
            $this->errorMsg['code'] = 0;
            $this->errorMsg['msg'] = 'token is empty';
            return response()->json($this->errorMsg);
        }

        $userId = JwtService::verifyToken($token);
        if(empty($userId)){
            $this->errorMsg['code'] = 0;
            $this->errorMsg['msg'] = 'token is invalid';
            return response()->json($this->errorMsg);
        }

        $userInfo = (new WechatUserDao())->getOne(['id' => $userId]);
        $request->userInfo = $userInfo;
        return $next($request);
    }
}
